/**   
 *    
 * 项目名称：SmartKungFuService   
 * 类名称：GymDetailServlet   
 * 类描述：   课程详情接口
 * 创建人：zhangl  
 * 创建时间：2016年9月26日 下午4:33:11   
 * 修改人：zhangl   
 * 修改时间：2016年9月26日 下午4:33:11   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.servlet;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.dao.ClientAccomplishMapper;
import com.lst.dao.MstCodeMapper;
import com.lst.entity.request.GymDetailReqPara;
import com.lst.entity.response.GymDetailResPara;
import com.lst.model.ClientAccomplish;
import com.lst.model.ClientGrowthUsed;
import com.lst.model.ClientNum;
import com.lst.model.ClientRoll;
import com.lst.model.GymnasiumDetail;
import com.lst.model.MstCode;
import com.lst.model.MstGrade;
import com.lst.model.MstGymnasium;
import com.lst.model.MstOrder;
import com.lst.model.MstRoll;
import com.lst.model.OrderDetail;
import com.lst.service.ClientGrowthUsedService;
import com.lst.service.ClientNumService;
import com.lst.service.ClientRollService;
import com.lst.service.GymnasiumDetailService;
import com.lst.service.MstGradeService;
import com.lst.service.MstGymnasiumService;
import com.lst.service.MstOrderService;
import com.lst.service.MstRollService;
import com.lst.service.OrderDetailService;
import com.lst.utils.CommFunUtils;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;

/**
 * @ClassName: GymDetailServlet
 * @Description:课程详情接口
 * @author zhangl
 * @date 2016年9月26日 下午4:33:11
 *
 */
public class GymnasiumDetailServlet extends BaseServlet {

	/**
	 * @Fields serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private MstGymnasiumService mstGymnasiumService = ctx.getBean(MstGymnasiumService.class); 

	private GymnasiumDetailService gymnasiumDetailService = ctx.getBean(GymnasiumDetailService.class);

	private ClientRollService clientRollService = ctx.getBean(ClientRollService.class); 

	private MstRollService mstRollService = ctx.getBean(MstRollService.class);

	private ClientGrowthUsedService clientGrowthUsedService = ctx.getBean(ClientGrowthUsedService.class);

	private MstGradeService mstGradeService = ctx.getBean(MstGradeService.class);

	private ClientNumService clientNumService = ctx.getBean(ClientNumService.class);

	private MstOrderService mstOrderService = ctx.getBean(MstOrderService.class);

	private OrderDetailService orderDetailService = ctx.getBean(OrderDetailService.class);

	private ClientAccomplishMapper clientAccomplishMapper = ctx.getBean(ClientAccomplishMapper.class);

	private MstCodeMapper mstCodeMapper = ctx.getBean(MstCodeMapper.class);

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();
		logger.info("doPost begin: " + startDate);

		GymDetailResPara resPara = new GymDetailResPara();

		try {
			GymDetailReqPara reqPara = getReqPara(request);

			if(isCheckField(reqPara,resPara)){
				Integer gymdetailid = Integer.valueOf(reqPara.getGymdetailid());					
				String type = reqPara.getType();//优惠券类型				
				String userid = reqPara.getUserid();//用户ID
				//String Grade = reqPara.getGrade();//等级	

				PageBounds pageBounds = new PageBounds();			

				GymnasiumDetail gd = gymnasiumDetailService.selectByPrimaryKey(gymdetailid);

				MstGymnasium mg = mstGymnasiumService.selectByPrimaryKey(gd.getGymid());

				MstCode mc = mstCodeMapper.selectByPrimaryKey(gd.getCoursetype());
				gd.setCoursetypename(mc.getName());					

				Integer favoritenum = CommFunUtils.opNum(null, gd.getId(), CommCode.SYSTEM_CARESEL_RANGE_COURSE, CommCode.SYSTEM_COUNT_FAVORITE, clientNumService);
				//分享量
				Integer sharenum = CommFunUtils.opNum(null, gd.getId(), CommCode.SYSTEM_CARESEL_RANGE_COURSE, CommCode.SYSTEM_COUNT_SHARE, clientNumService);
				//浏览量	
				Map<String, Object> mgMap = new HashMap<String,Object>();

				mgMap.put("enabled", true);
				mgMap.put("isDeleted", false);	
				mgMap.put("numtype", CommCode.SYSTEM_COUNT_BROWSE);
				mgMap.put("actid", gymdetailid);
				mgMap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_COURSE);

				List<ClientNum> Browselist = clientNumService.queryByList(mgMap);

				Integer browsenum = 0;

				for(ClientNum n : Browselist){
					browsenum += n.getNum() == null ? 0 : n.getNum();
				}

				gd.setFavoritenum(favoritenum);
				gd.setSharenum(sharenum);
				gd.setBrowsenum(browsenum);

				//获取已经报名数量
				Map<String, Object> momap = new HashMap<String, Object>();

				momap.put("enabled", true);
				momap.put("isDeleted", false);				
				momap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_COURSE);
				momap.put("actid", gymdetailid);	

				List<MstOrder> moList =  mstOrderService.queryByList(momap, pageBounds);

				Integer countnum = 0;

				for(MstOrder m : moList){

					momap.clear();
					momap.put("enabled", true);
					momap.put("isDeleted", false);
					momap.put("orderid", m.getId());	

					List<OrderDetail> odlist = orderDetailService.queryByList(momap, pageBounds);

					if(CommCode.SYSTEM_ORDER_STATUS_WAIT.equals(odlist.get(0).getOrderstatus())){
						countnum += m.getNum() == null ? 0 : m.getNum();
					}
				}

				Integer leavenum = gd.getLimitnum() - countnum;

				if(leavenum>=0){
					gd.setLeavenum(leavenum);
				}else{
					gd.setLeavenum(0);
				}

				mgMap.clear();
				mgMap.put("enabled", true);
				mgMap.put("isDeleted", false);	
				mgMap.put("gdid", gymdetailid);

				//获取套餐
				List<GymnasiumDetail> cpslist = gymnasiumDetailService.queryByList(mgMap, pageBounds);

				if(!cpslist.isEmpty()){
					gd.setCps(cpslist.get(0).getCps());							
				}

				List<ClientNum> cns = null;//统计量	

				if(!StringUtils.isEmpty(userid)){
					//统计量
					Map<String, Object> mstgMap = new HashMap<String, Object>();

					mstgMap.put("enabled", true);
					mstgMap.put("isDeleted", false);
					mstgMap.put("numtype",CommCode.SYSTEM_COUNT_FAVORITE);				
					mstgMap.put("clientid", Integer.valueOf(userid));
					mstgMap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_COURSE);
					mstgMap.put("actid", gymdetailid);

					cns = clientNumService.queryByList(mstgMap);//查询统计量
				}

				if(null==cns||cns.size()==0){
					gd.setIsFavorite(false);
				}else{					
					gd.setIsFavorite(true);						
				}

				//随便看看							
				Map<String, Object> lookmap = new HashMap<String,Object>();

				lookmap.put("enabled", true);
				lookmap.put("isDeleted", false);
				lookmap.put("gymid", mg.getId());
				lookmap.put("orderByClause", "gd.updatedate desc");
				lookmap.put("start", 0);
				lookmap.put("size", 6);

				List<GymnasiumDetail> looklist = gymnasiumDetailService.queryList(lookmap, pageBounds);

				GymnasiumDetail d = null;
				
				for(GymnasiumDetail g : looklist){
					if(g.getId().equals(gd.getId())){
						d = g;	
						break;
					}
				}
				if(d == null){
					looklist.remove(looklist.get(looklist.size()-1));
					gd.setGymlist(looklist);
				}else{	
					looklist.remove(d);
					gd.setGymlist(looklist);
				}

				//等级，优惠券																		
				if(!StringUtils.isEmpty(userid)){

					List<ClientAccomplish> caplist = clientAccomplishMapper.queryByUser(Integer.valueOf(userid));

					Integer grade = caplist.get(0).getGrade();// 等级

					//我的等级
					Map<String, Object> cgMap = new HashMap<String, Object>();

					cgMap.put("enabled", true);
					cgMap.put("isDeleted", false);					
					cgMap.put("clientid", Integer.valueOf(userid));
					cgMap.put("gradeid", grade);

					List<ClientGrowthUsed> cglist = clientGrowthUsedService.queryByList(cgMap, pageBounds); 

					if(cglist.isEmpty()){

						List<MstGrade> mgs = mstGradeService.queryByList(cgMap, pageBounds);
						resPara.setMstgrade(mgs.get(0));//等级优惠券
					}					

					//我的优惠券
					Map<String, Object> mstMap = new HashMap<String, Object>();

					mstMap.put("enabled", true);
					mstMap.put("isDeleted", false);				
					mstMap.put("gdid", gymdetailid);
					mstMap.put("type", Integer.valueOf(type));
					mstMap.put("orderByClause", "mr.createdate desc");

					List<MstRoll> mrlist = 	mstRollService.queryByList(mstMap, pageBounds);

					List<MstRoll> mstrolllist = null;

					if(!mrlist.isEmpty()){

						mstrolllist = new ArrayList<MstRoll>();

						Map<String, Object> crMap = new HashMap<String, Object>();

						crMap.put("enabled", true);
						crMap.put("isDeleted", false);

						for(MstRoll mr : mrlist){						

							crMap.put("rollid", mr.getId());
							crMap.put("clientid", Integer.valueOf(userid));

							List<ClientRoll> crlist = 	clientRollService.queryList(crMap, pageBounds);

							if(crlist.isEmpty()){

								Date start = DateUtil.getFormatDate(mr.getStartdate(),DateUtil.ALL_DATE_HORIZONTAL);

								Date end = DateUtil.getFormatDate(mr.getEnddate(),DateUtil.ALL_DATE_HORIZONTAL);

								Date  currentDate = DateUtil.getFormatDate(startDate, DateUtil.ALL_DATE_HORIZONTAL);

								int days1 = (int)((currentDate.getTime()-start.getTime())/86400000);

								int days2 = (int)((end.getTime()-currentDate.getTime())/86400000);

								if(days1>=0&&days2>=0){

									mstrolllist.add(mr);
								}
							}								
						}							
					}
					gd.setMrList(mstrolllist);
				}
				resPara.setGym(mg);
				resPara.setGd(gd);
				resPara.setCode(CommCode.M_Y000000);
				resPara.setMessage(CommCode.M_Y000001);				
			}

		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}

		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
			logger.info(jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

			logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public GymDetailReqPara getReqPara(HttpServletRequest request) {

		GymDetailReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new GymDetailReqPara());

			reqPara = (GymDetailReqPara) baseRequest.clone();

			String gymdetailid = request.getParameter("gymdetailid");			
			String clientid = request.getParameter("userid");
			String grade = request.getParameter("grade");
			String type = request.getParameter("type");				

			logger.info("reqPara gymdetailid: " + gymdetailid);			
			logger.info("reqPara clientid: " + clientid);
			logger.info("reqPara grade: " + grade);
			logger.info("reqPara type: " + type);				

			reqPara.setGymdetailid(gymdetailid);			
			reqPara.setUserid(clientid);
			reqPara.setGrade(grade);
			reqPara.setType(type);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		GymDetailReqPara gdReqPara = (GymDetailReqPara) reqPara;
		GymDetailResPara gdResPara = (GymDetailResPara) resPara;

		if (StringUtils.isEmpty(gdReqPara.getGymdetailid())) {
			gdResPara.setCode(CommCode.M_A000000);
			gdResPara.setMessage(CommCode.M_E000029);
		} else if(StringUtils.isEmpty(gdReqPara.getType())){
			gdResPara.setCode(CommCode.M_A000000);
			gdResPara.setMessage(CommCode.M_E000003);
		} else{
			flag = true;
		}
		return  flag;
	}
}
